//
// (x) Henrique Jotha
//
// Cliente para requisições a amazon
//
package br.unirio.bsi.dsw.AuctionLoader.util.amazon;

import br.unirio.bsi.dsw.AuctionLoader.beans.util.amazon.AWSECommerceService;
import br.unirio.bsi.dsw.AuctionLoader.beans.util.amazon.AWSECommerceServicePortType;
import br.unirio.bsi.dsw.AuctionLoader.beans.util.amazon.ItemSearch;
import br.unirio.bsi.dsw.AuctionLoader.beans.util.amazon.ItemSearchRequest;
import br.unirio.bsi.dsw.AuctionLoader.beans.util.amazon.Items;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;
import javax.xml.ws.Holder;
import java.util.HashMap;
import javax.xml.ws.WebServiceRef;
import org.apache.commons.lang.StringEscapeUtils;

public class AmazonWebServiceUtils
{
  private static final String accessKeyId = "AKIAJ3AR42PUNLQ4IVXA";
  private static final String signKeyId = "7rRdaHRbnwYSPqCEDoPzwEZsvXd9xf8FTKrMRWi5";
    
  @WebServiceRef(wsdlLocation="http://webservices.amazon.com/AWSECommerceService/2010-12-01/AWSECommerceService.wsdl")
  AWSECommerceService awsecs;
  AWSECommerceServicePortType awsecs_port;
  
  // simple url cache
  private String cache_file = null;
  HashMap<String, String> url_cache = new HashMap<String, String>();
  
  private static AmazonWebServiceUtils instance = null;
  
  private AmazonWebServiceUtils()
  {
    try {      
    awsecs = new AWSECommerceService();
    awsecs.setHandlerResolver( new AwsHandlerResolver( signKeyId ) );
    awsecs_port = awsecs.getAWSECommerceServicePort();  
    }
    catch( Exception ex ){}
  }
  
  public static AmazonWebServiceUtils getInstance() {
    if( instance == null ) 
      instance = new AmazonWebServiceUtils();
    return instance;
  }

  // read cache file
  public void init_cache( String cache_file )
  {
    try {  
    this.cache_file = cache_file;
    ObjectInputStream obj = new ObjectInputStream(new FileInputStream(cache_file));
		url_cache = (HashMap<String, String>)obj.readObject();
    obj.close();    
    }
    catch( Exception ex )
    {
      System.out.println(ex);
    }    
  }

  public void add_cache( String artist, String album, String url )
  {
    url_cache.put( artist+album, url );
  }
  
  // save cache file
  public void save_cache()
  {
    try {
    ObjectOutputStream obj = new ObjectOutputStream(new FileOutputStream(cache_file));
		obj.writeObject(url_cache);
		obj.close();  
    }
    catch( Exception ex )
    {
      System.out.println(ex);
    }
  }   
    
  public String getAlbumArtURL( String artist, String album )
  {
    String url_key = artist+album;
    if( url_cache.containsKey( url_key ) )
      return url_cache.get( url_key );
    
    ItemSearchRequest req = new ItemSearchRequest();
    req.setSearchIndex("Music");
    req.getResponseGroup().add("Images");
    //req.getResponseGroup().add("ItemAttributes");
    //req.getResponseGroup().add("Large");    

    artist = StringEscapeUtils.unescapeHtml(artist);
    album = StringEscapeUtils.unescapeHtml(album);

    //req.setArtist(artist);
    //req.setTitle(album);
    req.setKeywords(artist + " " + album);

    ItemSearch search = new ItemSearch();
    search.getRequest().add( req );
    search.setAWSAccessKeyId( accessKeyId );
      
    // texas hold'em
    Holder< List<Items> > items = new Holder< List<Items> >();

    try 
    {
      awsecs_port.itemSearch( search.getMarketplaceDomain(),
                       search.getAWSAccessKeyId(),
                       search.getSubscriptionId(),
                       search.getAssociateTag(),
                       search.getXMLEscaping(),
                       search.getValidate(),
                       req,
                       search.getRequest(), 
                       null,
                       items );    
      //
      List<Items> resp = items.value;
      String url = "";
      
      try {
        url = resp.get(0).getItem().get(0).getSmallImage().getURL();
        url_cache.put(url_key, url);
      }
      catch(Exception ex)
      {
        System.out.println("error:" + artist + " $$$ " + album);      
      }
      
      return url;
    } 
    catch( Exception ex )
    {
      System.out.println(ex);
      System.out.println("error:" + artist + " $$$ " + album);          
    }

    return null;
  }   
}
